<template>
  <view class="base-container">
    <mt-navbar title="新用户注册"></mt-navbar>
    <view class="register-box mt-56rpx px-32rpx">
      <uv-form ref="registerFormRef" label-position="top" :model="registerForm" :rules="rules" label-width="auto">
        <mt-title title="设置地区"> </mt-title>
        <uv-form-item prop="userInfo.registerZone" class="mb-56rpx">
          <!-- <view class="w-100% flex" style="position: relative">
            <uni-data-picker
              v-slot="{ data }"
              v-model="registerForm.userInfo.registerZone"
              placeholder="请选择所在地区"
              popup-title="选择所在地区"
              :localdata="city"
              :map="{ text: 'name', value: 'code' }"
            >
              <view class="city-box flex">
                <template v-if="data.length">
                  <view v-for="(item, index) in data" :key="index" class="mb-12rpx text-28rpx text-#1c213e"
                    >{{ item.text }}{{ index === 0 ? '- ' : '' }}
                  </view>
                </template>
                <view v-else class="tips-title mb-12rpx">请选择你的地区</view>
              </view>
              <uv-icon name="arrow-right" color="#1c213e" size="16" style="position: absolute; right: 0; top: 32rpx" class="pr-32rpx"></uv-icon>
            </uni-data-picker>
          </view> -->
          <view class="city-box w-100% flex" style="position: relative" @click="goSearchAddress">
            <view>
              <text v-if="registerForm.userInfo.registerZone" class="text-28rpx text-#1A1A1A">
                {{ updateCityData ? `${updateCityData.province}-${updateCityData.city}` : '请选择你的地区' }}
              </text>
              <text v-else class="text-28rpx text-#c0c4cc">请选择地区</text>
            </view>
            <uv-icon
              name="arrow-right"
              color="#1C213E"
              size="28rpx"
              style="position: absolute; right: 0; top: 32rpx"
              class="pr-32rpx"
              @click.stop="goSearchAddress"
            ></uv-icon>
          </view>
        </uv-form-item>

        <mt-title title="设置账户名"></mt-title>
        <uv-form-item prop="userInfo.providerName" class="mb-56rpx">
          <view class="w-100%">
            <uv-input v-model="registerForm.userInfo.providerName" border="bottom" placeholder="请输入账户名" maxlength="20"> </uv-input>
            <view class="mt-16rpx text-#727687 text-24rpx ml-24rpx">长度4-20位，仅支持汉字、字母、数字的组合</view>
          </view>
        </uv-form-item>

        <mt-title title="设置并确认密码"></mt-title>
        <uv-form-item prop="userInfo.password">
          <view class="w-100% pr-32rpx" style="position: relative">
            <uv-input
              v-model="registerForm.userInfo.password"
              :password="passwordFlag"
              class="w-100%"
              border="bottom"
              placeholder="设置你的密码"
              maxlength="20"
            >
            </uv-input>
            <!-- <template #right>
              <uv-icon name="arrow-right" color="#1c213e" size="16" class="pr-32"></uv-icon>
            </template> -->
            <view class="mt-16rpx text-#727687 text-24rpx ml-24rpx"
              >8-20位字母、数字、半角符号，不能是10位以下纯数字/字母/半角符号。字母需要区分大小写</view
            >
            <uv-icon
              style="position: absolute; right: 0; top: 0"
              :name="
                passwordFlag
                  ? 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-eyes-close.svg'
                  : 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-eyes-open.svg'
              "
              color="#1c213e"
              size="16"
              class="pr-32rpx pt-32rpx"
              @click="passwordFlag = !passwordFlag"
            ></uv-icon>
          </view>
        </uv-form-item>

        <uv-form-item prop="userInfo.againPassword" class="mb-56rpx">
          <view class="w-100%" style="position: relative">
            <uv-input
              v-model="registerForm.userInfo.againPassword"
              :password="againPasswordFlag"
              border="bottom"
              placeholder="再次确认你的密码"
              maxlength="20"
            >
            </uv-input>
            <view class="mt-16rpx text-#727687 text-24rpx ml-26rpx">确定设置的密码无误</view>
            <uv-icon
              style="position: absolute; right: 0; top: 0"
              :name="
                againPasswordFlag
                  ? 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-eyes-close.svg'
                  : 'https://mingtu-resources.oss-cn-shenzhen.aliyuncs.com/mtym-app-assets/icon-eyes-open.svg'
              "
              color="#1c213e"
              size="16"
              class="pr-32rpx pt-32rpx"
              @click="againPasswordFlag = !againPasswordFlag"
            ></uv-icon>
          </view>
        </uv-form-item>
        <mt-title title="邀请码"></mt-title>
        <uv-form-item class="mb-56rpx">
          <uv-input v-model="registerForm.userInfo.inviteCode" border="bottom" placeholder="请输入邀请码，没有可不填"></uv-input>
        </uv-form-item>
      </uv-form>
    </view>
    <view class="register-footer px-32rpx safety-16">
      <uv-checkbox-group v-model="agreementProtocolFlag">
        <ReadAgreement ref="readAgreementRef" v-model="agreementProtocolFlag" @confirm="handleRegister"></ReadAgreement>
        <mt-button class="mt-38rpx w-100%" style="border-radius: 192rpx" @click="handleRegister">提交注册</mt-button>
      </uv-checkbox-group>
    </view>
    <mt-popup ref="mtPopUpRef"></mt-popup>
  </view>
</template>

<script setup>
import { register, login } from '@/api/login.js';
import ReadAgreement from '@/pages/login/components/ReadAgreement.vue';
import { onLoad } from '@dcloudio/uni-app';
import { userCheck, passwordCheck } from '@/utils/regular.js';

const updateCityData = ref({});

const registerFormRef = ref(null);
const readAgreementRef = ref(null);
const mtPopUpRef = ref(null);

const passwordFlag = ref(true);
const againPasswordFlag = ref(true);
const registerForm = ref({
  userInfo: {
    phone: undefined,
    phoneTempCode: undefined,
    registerZone: undefined,
    providerName: undefined,
    password: undefined,
    againPassword: undefined,
    wechatTempCode: undefined,
    appleTempCode: undefined,
    inviteCode: undefined
  }
});
const agreementProtocolFlag = ref([]);

const rules = ref({
  'userInfo.registerZone': {
    type: 'string',
    required: true,
    message: '请选择地区',
    trigger: ['blur', 'change']
  },
  'userInfo.providerName': [
    {
      type: 'string',
      required: true,
      message: '请输入账户名',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        return userCheck(value);
      },
      message: '账户名长度4-20位，仅支持汉字、字母、数字的组合，请重新输入',
      trigger: ['blur']
    }
  ],
  'userInfo.password': [
    {
      type: 'string',
      required: true,
      message: '请输入密码',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        return passwordCheck(value);
      },
      message: '密码由 8 到 20 位的字母、数字或半角符号组成的字符串，并且确保该字符串不是 10 位以下的纯数字、纯字母或纯半角符号',
      trigger: ['blur']
    }
  ],
  'userInfo.againPassword': [
    {
      type: 'string',
      required: true,
      message: '请再次输入密码',
      trigger: ['blur', 'change']
    },
    {
      validator: (rule, value, callback) => {
        if (registerForm.value.userInfo.password !== value) return false;
      },
      message: '两次输入的密码不一致',
      trigger: ['blur']
    }
  ]
});

const handleRegister = () => {
  registerFormRef.value.validate().then((res) => {
    if (agreementProtocolFlag.value && agreementProtocolFlag.value.length) {
      const params = JSON.parse(JSON.stringify(registerForm.value.userInfo));
      register(params).then((res) => {
        if (res.code === 200) {
          uni.showToast({
            title: '注册成功',
            icon: 'none'
          });
          setTimeout(() => {
            // 注册成功直接登录
            login({ account: registerForm.value.userInfo.providerName, password: registerForm.value.userInfo.password }).then(() => {
              uni.navigateTo({
                url: '/pages/index/index'
              });
              uni.showToast({
                title: '登录成功',
                icon: 'none'
              });
            });
          }, 500);

          // 跳转到去登录
          // uni.reLaunch({
          //   url: '/pages/login/phoneQuick'
          // });
        }
      });
    } else {
      readAgreementRef.value.openTips();
    }
  });
};

// 监听城市变化并修改
uni.$on('getSelectCityData', async (item) => {
  updateCityData.value = item;
  registerForm.value.userInfo.registerZone = item.cityCode.toString();
});

onUnload(() => {
  // 移除监听事件 优化性能
  uni.$off('getSelectCityData');
});

// 注册地区填写
function goSearchAddress() {
  uni.setStorageSync('selectCity', {
    provinceCode: '',
    province: '',
    cityCode: '',
    city: ''
  });
  uni.navigateTo({
    url: '/pages/common/selectCity'
  });
}

onLoad((data) => {
  const { wechatTempCode, appleTempCode, phoneTempCode, phone } = data;
  if (data && data.type === 'wx') {
    registerForm.value.userInfo.wechatTempCode = wechatTempCode;
    registerForm.value.userInfo.phone = phone;
  } else if (data && data.type === 'apple') {
    registerForm.value.userInfo.wechatTempCode = appleTempCode;
    registerForm.value.userInfo.phone = phone;
  } else {
    registerForm.value.userInfo.phoneTempCode = phoneTempCode;
    registerForm.value.userInfo.phone = phone;
  }
});
</script>

<style lang="scss" scoped>
.base-container {
  min-height: 100vh;
  background: #ffffff;
  position: fixed;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  overflow-x: hidden;
  overflow-y: scroll;
  .register-box {
    padding-bottom: 20rpx;
    .title {
      font-weight: bold;
      font-size: 28rpx;
      &::before {
        content: ' ';
        padding: 0 2px;
        background-color: #447fee;
      }
    }
    .city-box {
      height: 96rpx;
      border-bottom: 1px solid #dadbde !important;
      display: flex;
      align-items: center;
      padding-left: 22rpx;
      .tips-title {
        color: rgb(192, 196, 204);
      }
    }
  }

  .register-footer {
    background-color: #fff;
    // position: fixed;
    // bottom: 16rpx;
  }
}
:deep(.uv-form-item__body__right__message) {
  margin-left: 26rpx !important;
}
:deep(.uv-input__content__field-wrapper__field) {
  padding: 17rpx 0;
}
</style>
